<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <div style="margin: 0 0 20px 0;">
      <el-select v-model="templateId" placeholder="请选择属性模板" style="width: 300px;"
                 @change="loadAttributeList">
        <el-option
            v-for="item in attributeTemplateListOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-button type="primary" size="medium" style="margin-left:20px;"
      @click="$router.push('/sys-admin/product/attribute/add-new?templateId='+templateId)">添加属性</el-button>
    </div>

    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="ID" width="150" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" width="150" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="类型" width="150" align="center">
        <template slot-scope="scope">
          <span v-text="typeText[scope.row.type]"></span>
        </template>
      </el-table-column>
      <el-table-column label="输入类型" width="100" align="center">
        <template slot-scope="scope">
          <span v-text="inputTypeText[scope.row.inputType]"></span>
        </template>
      </el-table-column>
      <el-table-column prop="valueList" label="备选值列表" width="250"  align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="unit" label="计量单位" width="80" align="center"></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="80" align="center"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-edit" circle type="primary"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="small" icon="el-icon-delete" circle type="danger"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编辑属性" :visible.sync="dialogFormVisible"
               @closed="resetForm('editForm')">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="130px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <template>
            <el-radio-group v-model="editForm.type">
              <el-radio :label="0">非销售属性
                <el-tooltip class="item" effect="dark" content="对商品销售不产生影响，但应补充说明的属性，例如：手机的产地" placement="top">
                  <i class="el-icon-info" style="color: #aaa"></i>
                </el-tooltip>
              </el-radio>
              <el-radio :label="1">销售属性
                <el-tooltip class="item" effect="dark" content="必须确定属性的值才可以进行商品销售的属性，例如：手机的内存容量" placement="top">
                  <i class="el-icon-info" style="color: #aaa"></i>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item label="输入类型" prop="inputType">
          <template>
            <el-radio-group v-model="editForm.inputType">
              <el-radio :label="0">手动录入</el-radio>
              <el-radio :label="1">单选</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item label="备选值列表" prop="valueList">
          <el-input v-model="editForm.valueList"></el-input>
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="editForm.unit"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 属性模板的下拉菜单的选项数据
      attributeTemplateListOptions: [],
      // 属性模板ID
      templateId: '',
      // 显示文本常量
      typeText: ['非销售属性', '销售属性'],
      inputTypeText: ['手动录入', '单选', '多选', '单选（下拉列表）', '多选（下拉列表）'],
      // 表格数据
      tableData: [],
      dialogFormVisible: false,
      editForm: {},
      rules: {
      }
    }
  },
  methods: {
    loadAttributeTemplateList(){
      let url = "http://localhost:9480/attribute-templates?queryType=all";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.attributeTemplateListOptions = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    loadAttributeList(){
      let url = "http://localhost:9480/attributes/list-by-template?queryType=all&templateId=" + this.templateId;
      console.log("url", url)

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.tableData = jsonResult.data.list;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    openEditDialog(attribute){
      let url = "http://localhost:9480/attributes/"+ attribute.id;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAttributeList();
            }
          });
        }
      });
    },
    submitEditForm(){
      let url = "http://localhost:9480/attributes/" + this.editForm.id + "/update";
      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify({
            title: '提示',
            message: '编辑属性成功！'
          });
          this.dialogFormVisible = false;
          this.loadAttributeList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadAttributeList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    openDeleteConfirm(attribute) {
      this.$confirm('此操作将永久删除【 ' + attribute.id + '-' + attribute.name + ' 】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(attribute);
      }).catch(() => {
      });
    },
    handleDelete(attribute){
      let url = "http://localhost:9480/attributes/" + attribute.id + "/delete";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.loadAttributeList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAttributeList();
            }
          });
        }else if(jsonResult.state == 40900){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadAttributeTemplateList();
    //this.loadAttributeList();
  }
}
</script>